<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true">
        <el-form-item label="应用系统：">
          <el-input v-model="search.systemName" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="所属单位：">
          <el-input v-model="search.company" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchQuery">查询</el-button>
          <el-button type="info" @click="search = {}; searchQuery();">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      ref="qmTable"
      :data="query"
      keyProp="systemId"
      menuType="text"
      useFormPage
      :menuOptions="{ width: 180 }"
    >
      <qm-table-column field="systemName">应用系统</qm-table-column>
      <qm-table-column field="company">所属单位</qm-table-column>
      <qm-table-column field="clientId">客户端ID</qm-table-column>
      <qm-table-column field="clientSecret">密钥</qm-table-column>
      <qm-table-column field="maxLoginUsersCount" width="120px">最大登录数</qm-table-column>
      <qm-table-column field="createdDate" width="160px">创建时间</qm-table-column>
      <!-- <qm-table-column field="createdUserName" width="120px" sortable="true">创建人</qm-table-column> -->
      <!-- <qm-table-column field="contacter" width="120px" sortable="true">联系人</qm-table-column> -->
      <!-- <qm-table-column field="telephone" width="120px">联系方式</qm-table-column> -->
      <qm-table-column field="isEnabled" width="100px" fieldType="enabledisable">是否开启</qm-table-column>

      <template v-slot:toolbar>
        <!-- 表格上面的工具栏，可自行添加和业务相关的按钮 -->
      </template>
      <template v-slot:moreBtn="{ row }">
        <!-- 列表操作列，可自行添加和业务相关的按钮 -->
        <el-dropdown>
          <el-button style="padding-left: 7px;" size="mini" type="text">更多</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="distributeUser(row)">分配用户</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </qm-table>

    <el-dialog
      :title="row.systemName + '分配用户'"
      :visible.sync="dialogUserVisible"
      @closed="dialogUserClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-row>
        <el-col :span="8">
          <el-select
            v-model="searchUsers"
            value-key="value"
            multiple
            filterable
            remote
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
          >
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="`${item.label}（${item.loginId}）`"
              :value="item"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button :loading="loading" type="primary" @click="addNew" icon="el-icon-plus">添加</el-button>
        </el-col>
      </el-row>
      <qm-table
        ref="dialogQmTable"
        v-if="dialogUserVisible"
        :urls="{query:'/sso/ssoSystem/setUsers/query'}"
        :beforeQuery="beforeQuery"
        :showView="false"
        :showEdit="false"
        :showDelete="false"
      >
        <qm-table-column field="userName" sortable>用户名称</qm-table-column>
        <template v-slot:moreBtn="{ row }">
          <el-button @click="doRemove(row)">移除</el-button>
        </template>
        <template v-slot:toolbar>
          <!-- 表格上面的工具栏，可自行添加和业务相关的按钮 -->
          <el-row style="margin-top: 15px;">
            <el-col :span="8">
              <el-input v-model="name" placeholder="请输入姓名"></el-input>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-button size="mini" type="primary" @click="selectByName" icon="el-icon-search">查询</el-button>
              <el-button
                size="mini"
                type="info"
                @click="name = ''; selectByName();"
                icon="el-icon-refresh"
              >重置</el-button>
            </el-col>
          </el-row>
        </template>
      </qm-table>
    </el-dialog>
  </div>
</template>

<script>
import Controller from "@/libs/framework/controller";
import request from "@/utils/request";

export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      model: "/sso/ssoSystem/getListModel",
      query: "/sso/ssoSystem/query",
      save: "/sso/ssoSystem/save",
      delete: "/sso/ssoSystem/delete",
      entity: "/sso/ssoSystem/getEntity",
    };
  }

  mixin() {
    return {
      data() {
        return {
          loading: false,
          name: null,
          //分配用户dialog的数据
          dialogUserVisible: false,
          searchUsers: [],
          //下拉框数据
          users: [],
          //当前行对象
          row: {},
        };
      },
      methods: {
        selectByName() {
          this.$refs["dialogQmTable"].refresh();
        },
        distributeUser(row) {
          this.row = row;
          this.dialogUserVisible = true;
          this.remoteMethod();
        },
        dialogUserClose() {
          this.dialogUserVisible = false;
          this.searchUsers = [];
          this.row = {};
        },
        beforeQuery(parmas) {
          parmas.query.systemId = this.row.systemId;
          if (this.name != "") {
            parmas.query.name = this.name;
          }
        },
        remoteMethod(query) {
          request({
            url: "/admin/sysRole/setUsers/userSelect2",
            method: "get",
            params: { term: query },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.users = r.data.map((m) => {
                  return {
                    value: m.userId,
                    userId: m.userId,
                    label: m.userName,
                    loginId: m.loginId,
                  };
                });
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        addNew() {
          if (null == this.searchUsers || this.searchUsers.length == 0) {
            this.$message("请先选择授予的人员!");
            return;
          }
          this.searchUsers.forEach((item) => {
            delete item.label;
            delete item.value;
          });
          this.loading = true;
          request({
            url: "/sso/ssoSystem/addUsersForQmui",
            method: "post",
            data: {
              systemId: this.row.systemId,
              users: this.searchUsers,
            },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.loading = false;
                this.$refs["dialogQmTable"].refresh();
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        doRemove(row) {
          this.$confirm("确定要移除么？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              request({
                url: "/sso/ssoSystem/removeUser",
                method: "get",
                params: {
                  id: row.Id,
                  userId: row.userId,
                  systemId: row.systemId,
                },
              })
                .then((r) => {
                  if (r && !r.initMessage) {
                    this.$message({
                      message: "删除成功",
                      type: "success",
                    });
                    this.$refs["dialogQmTable"].refresh();
                  } else {
                    reject(r.initMessage || "数据请求失败");
                  }
                })
                .catch((e) => {
                  reject(e);
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        },
      },
    };
  }
}
</script>

<style scoped lang="scss">
</style>
